Preventing Margin Collapsing Between Parent and Child Elements
Margin collapsing occurs when the vertical margins of a parent and its first or last child element merge into a single margin. This often reduces the expected spacing, especially when designing nested layouts.
In this case, the top margin of the child merges with the parent's top edge. The margin doesn’t create space inside the parent; instead, it pushes the parent itself downward.
Add padding to the parent (e.g., padding-top: 1px;).
Add a border to the parent (even border: 1px solid transparent; works).
Use overflow: auto; or overflow: hidden; on the parent to create a new block formatting context.
Set display: flow-root; on the parent element.
Use display: flex; or display: grid; — margins don’t collapse in these layouts.
These techniques ensure the parent and child margins remain independent, giving you full control over spacing inside nested elements.